package gui.lesson03;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;

public class TestMouseListener {
    //鼠标监听事件
    public static void main(String[] args) {
        new MyFrame("画图");
    }
}
//创建一个自己的类
class MyFrame extends Frame{
    ArrayList points;
    //需要画笔，监听鼠标点击的点，需要集合来存储这个点
    public MyFrame(String title){
        super(title);
        setBounds(200,200,400,400);
        setVisible(true);
        //集合中存放鼠标点击的点
        points=new ArrayList<>();
        //鼠标监听器，针对该窗口
        this.addMouseListener(new MyMouseListener());
    }
    @Override
    public void paint(Graphics g) {
        //画笔，监听鼠标的事件
        Iterator iterator = points.iterator();
        while (iterator.hasNext()){
            Point point = (Point) iterator.next();
            g.setColor(new Color(19, 227, 196));
            //画笔要画的事件，xy为坐标，后两个为间距
            g.fillRect(point.x,point.y,10,10);
        }
    }
    //添加一个点到界面上
    public void addPaint(Point point){
        points.add(point);
    }
    //适配器模式
    private class MyMouseListener extends MouseAdapter{
        //鼠标的三种状态，按下，弹起，按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame frame = (MyFrame) e.getSource();
            //我们点击的时候，页面上就会产生一个点
            //这个点就是鼠标的点
            frame.addPaint( new Point(e.getX(),e.getY()));
            //每次点击鼠标都需要重新画一遍
            frame.repaint();//刷新
        }
    }
}